package cn.com.fssg.platform.base.handler.impl.cl.fuju;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class ClFujuApplyItemInterfaceHandler implements InterfaceHandler {
        private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantJdbcTemplate("CJRLHHConnString");
//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    private final int COUNT = 1;
    private final String APPLY_ID = "empty_id";
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        //提交辅具申请前先保存辅具详细信息
        JSONArray jsonArray = jsonObject.getJSONArray("items");
        if (ObjectUtils.isEmpty(jsonArray)) {
            return null;
        }
        StringBuilder builder = new StringBuilder("insert into cl_apply_fuju_item (");
        builder.append("id, money, apply_status, apply_id,");
        builder.append("fuju_cat, fuju_id, count, fuju_type,");
        builder.append("create_by, create_time, update_by, update_time)");
        builder.append("values ('%s', %s,'%s', '%s',");
        builder.append("'%s', '%s', %s, '%s',");
        builder.append("'%s', '%s', '%s', '%s')");
        String baseSql = builder.toString();
        String userId = BizUtil.cur().curUserId();
        String time = format.format(new Date());
        Map<String, Object> params = new HashMap<>();
        try{
            jsonArray.stream().forEach(item -> {
                JSONObject itemJson = (JSONObject) item;
                Object hujuId = itemJson.get("huju_id");
                String hujuTypeId = itemJson.getString("huju_type_id");
                String sql = String.format(baseSql,
                        UUID.randomUUID(), itemJson.getInteger("max_money_rule"), "0", APPLY_ID,
                        itemJson.getString("fuju_cat"), ObjectUtils.isEmpty(hujuId)? "": hujuId, COUNT, hujuTypeId,
                        userId, time, userId, time
                        );
                jdbcTemplate.update(sql, params);
            });

        } catch (Exception e) {
            return "jdbc:" + jdbcTemplate + ";" + e.getMessage();
        }
        return true;
    }
}
